package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.util.Page;
import com.changgou.util.Result;
import com.changgou.util.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @ClassName: SkuController
 * @Author: ZWJ
 * @Date: 2020-09-01 18:03
 * @Synopsis: Null
 **/
@Controller
@RequestMapping("/search")

public class SkuController {
    @Autowired
    private SkuFeign skuFeign;
    @GetMapping("/list")
    public String search(@RequestParam(required = false) Map<String,String> searchMap, Model model) throws Exception {
        Result searchResult = skuFeign.search(searchMap);
        //获取搜索的数据
        Map data = (Map)searchResult.getData();
        model.addAttribute("result",data);
        //页面关键词的回显需要知道参数
        model.addAttribute("searchMap",searchMap);
        //进行url的拼接
        String url = getUrl(searchMap);
        model.addAttribute("url",url);
        model.addAttribute("sortUrl", UrlUtils.replateUrlParameter(url,"sortRule","sortField","pageNum"));
        //分页需要数据
        Integer pageNum = (Integer)data.get("pageNum");
        Integer pageSize = (Integer)data.get("pageSize");
        String totalElements = data.get("totalElements").toString();
        Long aLong = Long.valueOf(totalElements);
        Page<SkuInfo> page=new Page<SkuInfo>( aLong,pageNum,pageSize);
        long last = page.getLast();//最后一页
        model.addAttribute("last",last);
        long next = page.getNext();//下一页
        model.addAttribute("pageNext",next);
        long upper = page.getUpper();//上一页
        model.addAttribute("upper",upper);

        model.addAttribute("page",page);

        return "search";
    }
    //处理url
    public String getUrl(Map<String,String> searchMap){
        //url
        String url="/search/list";
        if (searchMap!=null){
            url=url+"?";
            for (Map.Entry<String, String> stringStringEntry : searchMap.entrySet()) {
                String key = stringStringEntry.getKey();
                String value = stringStringEntry.getValue();
                url=url+key+"="+value+"&";
            }
        }
        //去掉最后一个&
         url = url.substring(0, url.length() - 1);
        url = UrlUtils.replateUrlParameter(url, "pageNum");

        return url;
    }
}
